import threading
import multiprocessing as mp
import time

"""
多进程编程功能测试
包含Value（全局变量）、Lock（进程锁，防止多个进程同时访问一个数据）
可在进程、类、线程中使用Value，并修改Value的值
"""
class DataReadThread(threading.Thread):
    def __init__(self, stopFlag: mp.Value, lock : mp.Lock()):
        threading.Thread.__init__(self)
        self.stopFlag = stopFlag
        self.lock = lock

    def run(self):
        i = 0
        while True:
            self.lock.acquire()
            time.sleep(0.5)
            i += 1
            self.stopFlag.value = i
            if i > 100:
                i = 0
            print("线程在运行！！")
            self.lock.release()

def run1(stopFlag: mp.Value, lock : mp.Lock()):
    data_read = DataReadThread(stopFlag, lock)
    data_read.start()
    while True:
        lock.acquire()  # 锁住
        time.sleep(1)
        print("run1:", stopFlag.value)
        lock.release()  # 释放

def run2(stopFlag: mp.Value, lock : mp.Lock()):
    while True:
        lock.acquire()  # 锁住
        time.sleep(1)
        print("run2:", stopFlag.value)
        lock.release()  # 释放

def run3(stopFlag):
    while True:
        time.sleep(1)
        print("run3:", stopFlag.value)

class RunTask():
    def __init__(self):
        self.stop_flag = mp.Value('i', 10)
        self.q_send = mp.Queue(2)
        self.lock = mp.Lock()

    def run(self):
        p_video = mp.Process(target=run1, args=(self.stop_flag, self.lock))
        p_cardev = mp.Process(target=run2, args=(self.stop_flag, self.lock))
        p_run3 = mp.Process(target=run3, args=(self.stop_flag,))

        p_run3.start()
        p_video.start()
        p_cardev.start()

        print("stop_flag0", self.stop_flag.value)
        p_video.join()
        p_cardev.join()
        print("stop_flag1", self.stop_flag.value)
        p_video.terminate()
        p_cardev.terminate()

if __name__ == "__main__":
    run_task = RunTask()
    run_task.run()